package com.marry.daodaomanage.infrastructure.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @author mal
 * @date 2022-11-23 15:51
 */
@Component
public class MyRequestInterceptor implements RequestInterceptor {
    public static final String AUTHORIZATION = "Authorization";
    @Override
    public void apply(RequestTemplate template) {
        ServletRequestAttributes requestAttributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
        if (requestAttributes!=null) {
            HttpServletRequest request = requestAttributes.getRequest();
            Enumeration<String> headerNames = request.getHeaderNames();
            if (headerNames!=null) {
                if (headerNames.hasMoreElements()) {
                    String name = headerNames.nextElement();
                    if (name.equalsIgnoreCase(AUTHORIZATION) && template.headers().entrySet().stream().noneMatch(p -> p.getKey().equals(AUTHORIZATION))) {
                        template.header(AUTHORIZATION, request.getHeader(AUTHORIZATION));
                    }

                }
            }


        }
    }
}
